package com.example.demo.demos.config;

import com.example.demo.demos.util.RedisUtil;
import com.example.demo.demos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession(false);
        if (session == null) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401}");
            return false;
        }
//        String username = (String) session.getAttribute("username");
        String sessionToken = (String) session.getAttribute("token");
        if ( sessionToken == null) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401}");
            return false;
        }
        String username = redisUtil.getToken(sessionToken);
        if (username==null || username.equals("")) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401}");
            return false;
        }
        // JPA方式权限校验
        String requestPath = request.getRequestURI();
        // 这里假设UserRepository有hasPermission方法
        // 可根据实际表结构调整
        boolean hasPermission = false;
        if (username != null && !username.isEmpty()) {
            // 例如：hasPermission = userRepository.existsByNameAndPermissionPath(username, requestPath);
            // 这里假设UserServiceImpl已改为JPA方式实现
            hasPermission = userService.hasPermission(username, requestPath);
        }
        if (!hasPermission) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("{\"code\":403}");
            return false;
        }
        return true;
    }
}
